package com.lightjet.macross.base.upms.service.impl;

import com.lightjet.macross.base.feign.api.domain.AuthUser;
import com.lightjet.macross.base.upms.domain.AppClient;
import com.lightjet.macross.base.upms.domain.RoleInfo;
import com.lightjet.macross.base.upms.service.AppClientService;
import com.lightjet.macross.base.upms.service.LoginAdapterService;
import com.lightjet.macross.base.upms.service.RoleUserLinkService;
import com.lightjet.macross.common.util.SpringUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.java.Log;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("sysUserAuthServiceImpl")
@Log
public class SysUserAuthServiceImpl implements UserDetailsService {

/*    @Autowired
    HttpServletRequest httpServletRequest;*/

    @Resource
    AppClientService appClientService;

    @Resource
    RoleUserLinkService roleUserLinkService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //username 形式 [超级用户名@]用户名[|适配器:客户端ID]
        log.info("开始认证用户【"+username+"】");
        String[] partsinfo = username.split("\\|");
        String clientid = ""; //默认使用 macross平台的人员验证适配器
        String adapter = "macross";
        if(partsinfo.length>1)
        {
            String[] subpaurtinfo = partsinfo[1].split(":");
            adapter = StringUtil.isNullOrEmpty(subpaurtinfo[0])? adapter : subpaurtinfo[0];
            if(subpaurtinfo.length>1)
            {
                clientid = StringUtil.isNullOrEmpty(subpaurtinfo[1])?clientid:subpaurtinfo[1];
            }
        }
        LoginAdapterService loginAdapterService = SpringUtil.getBean(adapter,LoginAdapterService.class);//获取登录适配器
        String[] unames =  partsinfo[0].split("@");
        String proxyed = "-";
        if(unames.length>1)
        {
            username = unames[1];
            proxyed = unames[0];
        }
        else
        {
            username = unames[0];
        }
        /*RowMapper rowMapper = new BeanPropertyRowMapper(AuthUser.class);
        List<AuthUser> user = bizJdbcTemplate.query(
                "select t.id,t.username,nvl((select u.password from ht802ct.hr802_emprole x left outer join ht802ct.hr802_userinfo u on u.empid = x.empid "+
        "where u.username = ? and x.roleid='1003000100000000000000000000000000000000'),t.password) as password,t.displayname,t.workno,t.email,t.orgid,t.orgname,t.unicode "+
        "from ht802ct.HR802_V_EMPS t where t.username = ?",new Object[]{ proxyed,username},rowMapper);*/
        AuthUser authUser = loginAdapterService.Authenticate(username,proxyed);
        if(authUser!=null) {
            log.info("认证用户【"+username+"】成功！");
            if(!StringUtil.isNullOrEmpty(clientid))
            {
                AppClient appClient = appClientService.FindByClientid(clientid);
                if(appClient!=null && !StringUtil.isNullOrEmpty(appClient.getClientname()))
                {
                    log.info("开始获取客户端ID【"+clientid+"】在UPMS【"+appClient.getClientname()+"】中的角色集合");
                    List<RoleInfo> roleInfoList = roleUserLinkService.FindBySystemShortNameAndUserKey(appClient.getClientname(),authUser.getId());
                    if(roleInfoList!=null && roleInfoList.size()>0)
                    {
                        List<String> roles = new ArrayList<>();
                        for(RoleInfo roleInfo : roleInfoList)
                        {
                            roles.add("ROLE_"+ (StringUtil.isNullOrEmpty(roleInfo.getRoledescription())?roleInfo.getRolename():roleInfo.getRoledescription()).toUpperCase());
                        }
                        authUser.setRoles(StringUtils.join(roles,","));
                    }
                }
            }
            //user.get(0).setBeanname("ht802");
            return authUser;
        }
        else
        {
            log.info("认证失败【"+username+"】");
            return null;
            /*UserAuthService one = new UserAuthService();
            one.setDisplayname("已注销账户");
            return one;*/
        }
    }

}
